//
//  AXFMapViewController.m
//  AXFEightGroup
//
//  Created by Haozhong Chen on 2016/12/24.
//  Copyright © 2016年 ya. All rights reserved.
//

#import "AXFMapViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#import "AXFLocationSearchViewController.h"
#import "AXFLocationManager.h"


static NSString*AXFAnnotationID=@"AXFAnnotation";

typedef void (^CallbackBlock)(CLPlacemark *placemark);

@interface AXFMapViewController ()<MKMapViewDelegate,CLLocationManagerDelegate,UISearchBarDelegate>

//@property(nonatomic,strong)NSMutableArray<CLPlacemark*>*placemarkArray;

@property(nonatomic,strong)CLLocationManager*locationManager;
@property(nonatomic,weak)AXFLocationSearchViewController*searchViewController;

@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@property (weak, nonatomic) IBOutlet UILabel *locationLabel;

@end

@implementation AXFMapViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    _locationLabel.hidden=YES;
//    [self setupCoreLocationManager];
    [self setupMapView];
    [self setupSearchView];
    
    
   
}

-(void)updateLocationManagerData
{
    
//    AXFDataModel*model=[[AXFDataModel alloc]init];
//    model.address=_placemarkArray.lastObject.name;
    
//    [[AXFLocationManager sharedInstance].dataArray addObject:model];
//    NSLog(@"%@",model.address);
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"kUpdateLocationManagerData" object:self];
    
}

-(void)setupSearchView
{
    AXFLocationSearchViewController*vc=[[AXFLocationSearchViewController alloc]init];
    [self addChildViewController:vc];
    [self.view addSubview:vc.view];
    
    [vc didMoveToParentViewController:self];
    
    _searchViewController=vc;
    [vc.view mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.top.equalTo(self.view.mas_top).offset(SCREEN_HEIGHT*0.7);
     }];
    
}

-(void)setupMapView
{
    self.mapView.delegate=self;
    self.mapView.userTrackingMode=MKUserTrackingModeFollow;
    self.mapView.mapType=MKMapTypeStandard;
    self.mapView.showsUserLocation=YES;
    self.mapView.showsScale=YES;
    self.mapView.showsCompass=YES;
    self.mapView.showsPointsOfInterest=YES;
    self.mapView.showsTraffic=YES;
    self.mapView.showsBuildings=YES;// 显示3D建筑(没用)
    
    
    UIGestureRecognizer*gesture=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(addAXFAnnotation:)];
    [self.mapView addGestureRecognizer:gesture];
    
}


- (void)zoomWithFactor:(float)factor
{
    MKCoordinateSpan zoomSpan=MKCoordinateSpanMake(self.mapView.region.span.latitudeDelta*factor, self.mapView.region.span.longitudeDelta*factor);
    [self.mapView setRegion:MKCoordinateRegionMake(self.mapView.region.center, zoomSpan) animated:YES];
}
- (IBAction)clickedConfirmButton:(id)sender
{
    if (_confirmBlock)
    {
        self.confirmBlock();
    }
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (IBAction)clickedZoomInButton:(id)sender
{
    [self zoomWithFactor:0.5];
}

- (IBAction)clickedZoomOutButton:(id)sender
{
    [self zoomWithFactor:2];
}

- (IBAction)clickedLocateButton:(id)sender
{
    
//    方法一 重设追踪模式
//    [_mapView setUserTrackingMode:MKUserTrackingModeFollow animated:YES];
//    方法二 重设mapView的region
    //region有两个属性
    //span跨度和center(坐标coordinate)
    //这个方法可以设置地图精度以及显示用户所在位置的地图
//    MKCoordinateRegion region=MKCoordinateRegionMake(_mapView.userLocation.location.coordinate, _mapView.region.span);
//    [_mapView setRegion:region animated:YES];
//    方法三 重设centerCoordinate为userLocation.location.coordinate
    //span默认不变
    [_mapView setCenterCoordinate:self.mapView.userLocation.location.coordinate animated:YES];
}


-(void)addAXFAnnotation:(UIGestureRecognizer*)gesture
{
    
    if (gesture.state != UIGestureRecognizerStateBegan)
    {
        return;
    }
    CGPoint point=[gesture locationInView:gesture.view];
    CLLocationCoordinate2D coordinate=[self.mapView convertPoint:point toCoordinateFromView:self.mapView];
    
    //地理位置反编码方法
    CLLocation*location=[[CLLocation alloc]initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    
    [self reverseGeocodeLocation:location AddAnnotationCallback:^(CLPlacemark *placemark)
    {
        MKPointAnnotation*annotaion=[[MKPointAnnotation alloc]init];
        [annotaion setCoordinate:location.coordinate];
        annotaion.title=placemark.name;
        annotaion.subtitle=placemark.subLocality;
        
        [self.mapView addAnnotation:annotaion];
    }];

}



-(void)reverseGeocodeLocation:(CLLocation*)location AddAnnotationCallback:(CallbackBlock)addAnnotationCallback
{
    // 1. 创建地理编码器
    CLGeocoder *coder = [CLGeocoder new];
//    __weak typeof(self)weakSelf=self;
    // 3. 进行反编码
    [coder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        // 4. 错误处理
        if(error != nil || placemarks == nil || placemarks.count == 0) {
            return ;
        }
        
        if (addAnnotationCallback)
        {
            addAnnotationCallback(placemarks.firstObject);
        }
        if (placemarks.firstObject.name!=nil)
        {
            
            [[AXFLocationManager sharedInstance].placemmarkArray addObject:placemarks.firstObject];
            NSLog(@"%@",placemarks.firstObject.name);
            [self updateLocationManagerData];
        }
        
        
    }];
}



-(void)setupCoreLocationManager
{
    
    
    CLAuthorizationStatus authorizationStatus=[CLLocationManager authorizationStatus];
    //
    if (authorizationStatus==kCLAuthorizationStatusNotDetermined)
    {
        if ([[UIDevice currentDevice].systemVersion doubleValue]>=8.0) {
            [self.locationManager requestWhenInUseAuthorization];
        }
    }
    else if(authorizationStatus == kCLAuthorizationStatusRestricted || authorizationStatus == kCLAuthorizationStatusDenied)
    {
        NSLog(@"提醒开启定位权限");
    }
    
    self.locationManager.desiredAccuracy=kCLLocationAccuracyBest;
    self.locationManager.distanceFilter=5;
    
    self.locationManager.delegate=self;
    [self.locationManager startUpdatingLocation];
    
    
}

-(CLLocationManager*)locationManager
{
    if (!_locationManager)
    {
        _locationManager=[[CLLocationManager alloc]init];
    }
    return _locationManager;
}


-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    [self.locationManager stopUpdatingLocation];
    CLLocation*location=locations.lastObject;
    
    CLGeocoder*geoCoder=[[CLGeocoder alloc]init];
//    __weak typeof(self)weakSelf=self;
    [geoCoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error)
    {
        NSLog(@"%@",placemarks.firstObject);
        if(error != nil || placemarks == nil || placemarks.count == 0) {
            NSLog(@"处理错误");
            return ;
        }
        
        
        NSMutableString *info = [NSMutableString string];;
        for (CLPlacemark *placemark in placemarks) {
            
            [info appendFormat:@"名称:%@\n",placemark.name];
            [info appendFormat:@"街道:%@\n",placemark.thoroughfare];
            [info appendFormat:@"省:%@\n",placemark.administrativeArea];
            [info appendFormat:@"市:%@\n",placemark.locality];
            [info appendFormat:@"国家:%@\n",placemark.country];
            
        }
//        _locationLabel.text=info;

    }];
    
    
    
    
}



//MKUserLocation是地图上大头针模型，有title和subtitle以及location信息。该方法调用频繁
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    
    CLLocation*location=userLocation.location;
    [self reverseGeocodeLocation:location AddAnnotationCallback:nil];
    [self.locationManager stopUpdatingLocation];
    CLGeocoder*geoCoder=[[CLGeocoder alloc]init];
    //    __weak typeof(self)weakSelf=self;
    [geoCoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error)
     {
         if(error != nil || placemarks == nil || placemarks.count == 0)
         {
             NSLog(@"处理错误");
             return ;
         }
         
         _locationLabel.text=[placemarks[0].locality stringByAppendingString:placemarks[0].name];
         _locationLabel.hidden=NO;
     }];

//    设置地图的中心和显示尺寸
    
//    NSLog(@"%f,%f",userLocation.location.coordinate.longitude,userLocation.location.coordinate.latitude);
    //点击大头针，会出现以下信息
    userLocation.title=@"中国";
    userLocation.subtitle=@"四大文明古国之一";
    
    //让地图显示用户的位置（iOS8一打开地图会默认转到用户所在位置的地图），该方法不能设置地图精度
    //    [mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];
    
}

//可以打印经纬度的跨度，用来测试当前视图下地经纬度跨度是多少，然后用于上面的MKCoordinateSpanMake方法中
-(void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    
   
    
}


//-(NSMutableArray<CLPlacemark*>*)placemarkArray
//{
//    if (_placemarkArray==nil)
//    {
//        _placemarkArray=[[NSMutableArray alloc]init];
//    }
//    
//    return _placemarkArray;
//}




// 2. 实现代理, 自定义大头针视图
//- (nullable MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
//{
//    
//    if ([annotation isKindOfClass:[MKUserLocation class]])
//    {
//        return nil;
//    }
//    MKPinAnnotationView * view = [[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:@"pin"];
//    view.pinColor=MKPinAnnotationColorGreen;
//    view.animatesDrop=YES;
//    return view;
//    
//}



-(void)dealloc
{
    NSLog(@"test cycle ratain");
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


@end
